/*  This program prepares data on pop, land area, and education for merging with the LBD and innov index.
    pop density 1980, bashares 1980

*/


log using "prep_dens_bashares.log", replace


global path "[redacted]"
global programs "${path}programs/"
global logs "${path}logs/"
global rawlbd "/projects/data/lbd/"
global imported "[redacted]"
global inter "${path}data/inter/"
global output "${path}data/output/"
global tables "${path}results/tables/"
global graphs "${path}results/graphs/"


********************
** LAND AREAS **

use ${imported}2014_Gaz_counties_national.dta, clear

rename geoid numfips
keep numfips aland_sqmi
tostring numfips, gen(fips)
replace fips = "0"+fips if length(fips)==4

save ${inter}fips_area.dta, replace

** END LAND AREAS **
********************

**************************
*** Prep BA holders **

use ${imported}nhgis0018_educ_ts_nominal_county.dta, clear

tostring statefp, gen(stfips)
tostring countyfp, gen(ctyfips)
replace stfips = "0"+stfips if length(stfips)==1
replace ctyfips = "0"+ctyfips if length(ctyfips)==2
replace ctyfips = "00"+ctyfips if length(ctyfips)==1
egen fips = concat(stfips ctyfips)
destring fips, gen(numfips)

* ba holders are b69ac1980
rename b69ac1980 ba1980
keep fips numfips ba1980

save ${inter}fips_ba1980.dta, replace


*** END Prep BA holders **
**************************

******************************************
** FOR DENSITY: TOTAL POP by FIPS, 1980 **

use ${imported}popbyage.dta, clear
*first line is var descrips
drop in 1

egen fips = concat(statefp countyfp)
destring fips, gen(numfips)

rename av0aa1980 pop1980
* calc county pop for persons 25 and older
foreach var in b57ai1980 b57aj1980 b57ak1980 b57al1980 b57am1980 b57an1980 b57ao1980 b57ap1980 b57aq1980 b57ar1980 {
   destring `var', replace
}
egen pop25plus1980 = rowtotal(b57ai1980 b57aj1980 b57ak1980 b57al1980 b57am1980 b57an1980 b57ao1980 b57ap1980 b57aq1980 b57ar1980)
keep fips numfips pop1980 pop25plus1980 state county

merge 1:1 fips using ${inter}fips_area.dta
drop if _m==2
drop _m

merge 1:1 fips using ${inter}fips_ba1980.dta
drop _m

destring pop1980, replace
* calc pop density
gen popdens = pop1980/aland_sqmi

* calc BA shares
gen bashare = ba1980/pop25plus1980

save ${inter}popdens_bashare_fips_1980.dta, replace



** END DENSITY **
******************************************



log close











